package com.xshang.mybatis;

import com.xshang.tenant.TenantDataSourceContext;
import com.zaxxer.hikari.HikariDataSource;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.concurrent.TimeUnit;

@Setter
@Configuration
@ConfigurationProperties(prefix = "spring.datasource.default-tenant")
public class DefaultTenantDataSourceAutoConfig {

    private String driverClassName;

    private String jdbcUrl;

    private String username;

    private String password;

    private int minimumIdle = 5;

    private int maximumPoolSize = 20;

    private boolean autoCommit = true;

    private long idleTimeout = TimeUnit.MILLISECONDS.toMillis(30000);

    private String poolName = "Mybatis-Tenant-HikariCP";

    private long maxLifetime = TimeUnit.MILLISECONDS.toMillis(1800000);

    private long connectionTimeout = TimeUnit.MILLISECONDS.toMillis(30000);

    private String connectionTestQuery = "SELECT 1";


    @Bean(name = TenantDataSourceContext.DEFAULT_TENANT_DATA_SOURCE)
    public DataSource tenantDataSource() {

        HikariDataSource hikariDataSource = DataSourceBuilder.create()
                .url(jdbcUrl)
                .username(username)
                .password(password)
                .driverClassName(driverClassName)
                .type(HikariDataSource.class).build();

        hikariDataSource.setConnectionTimeout(connectionTimeout);
        hikariDataSource.setIdleTimeout(idleTimeout);
        hikariDataSource.setMaximumPoolSize(maximumPoolSize);
        hikariDataSource.setAutoCommit(autoCommit);
        hikariDataSource.setIdleTimeout(idleTimeout);
        hikariDataSource.setPoolName(poolName);
        hikariDataSource.setConnectionTestQuery(connectionTestQuery);
        hikariDataSource.setMaxLifetime(maxLifetime);
        hikariDataSource.setMinimumIdle(minimumIdle);

        return hikariDataSource;

    }


}
